package it.blog.controller;

import java.util.List;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import it.blog.server.User;
import it.blog.stub.*;


public class BlogView extends HttpServlet{
		
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session =  request.getSession();
		Blog blog;
		List<Post> postList;
		Integer id= Integer.parseInt(request.getParameter("id"));
		String var= request.getParameter("var");	
		BlogPortal bp = new BlogPortalService().getPort(BlogPortal.class);
		session.removeAttribute("mess");
		session.removeAttribute("nPost");
		if(var.equals("blog")){
		   blog = bp.getBlog(id);
		   postList = bp.getPostsOfBlog(id);
		}
		else{
		   blog = bp.getBlogOfUser(id);
		   postList = bp.getPostsOfBlog(blog.getBlogID());
		}
		List<PostCategory> postCategoryList = bp.getPostCategoryListOfBlog(id);
		
		int postedUserID = blog.getBlogOwner();
		String usernameBlogOwner = bp.getPublicInfoUser(postedUserID).getUsername();
		String nameBlogOwner = bp.getPublicInfoUser(postedUserID).getName();
		String surnameBlogOwner = bp.getPublicInfoUser(postedUserID).getSurname();
		String mailBlogOwner = bp.getPublicInfoUser(postedUserID).getEmail();
		
		request.getSession().setAttribute("usernameBlogOwner", usernameBlogOwner);
		request.getSession().setAttribute("nameBlogOwner", nameBlogOwner);
		request.getSession().setAttribute("surnameBlogOwner", surnameBlogOwner);
		request.getSession().setAttribute("mailBlogOwner", mailBlogOwner);

		request.getSession().setAttribute("blog",blog);		
		request.getSession().setAttribute("postList",postList);	
		if(postList.size()<=0){
			session.setAttribute("mess","Non sono presenti post");		
		}else{
			session.setAttribute("nPost",postList.size());		

		}
		//PAGINATION
		Integer currentPage= Integer.parseInt(request.getParameter("p"));
		int itemForPage=4;
		int nPage=(int)Math.ceil(((double)postList.size()/itemForPage));
		int first=(currentPage-1)*itemForPage;
		int last=first+itemForPage-1;
		int vect[]={currentPage,nPage,first,last};
		session.setAttribute("paginationPost", vect);
		request.getSession().setAttribute("postCategoryList", postCategoryList);
		response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/home.jsp?kop=blog"));
	}

}
